<template>
  <div class="scene-list">
    <div class="header">
      <el-button type="primary" @click="handleAdd">
        创建场景
      </el-button>
    </div>

    <el-table :data="scenes" v-loading="loading">
      <el-table-column prop="name" label="场景名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'info'">
            {{ row.status ? '已激活' : '未激活' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleActivate(row)">
            激活
          </el-button>
          <el-button link type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="form.id ? '编辑场景' : '创建场景'"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="场景名称" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="设备" required>
          <div v-for="(device, index) in form.devices" :key="index" class="device-item">
            <el-select v-model="device.deviceId" placeholder="选择设备">
              <el-option
                v-for="item in devices"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-switch v-model="device.targetStatus" />
            <el-button link type="danger" @click="removeDevice(index)">
              删除
            </el-button>
          </div>
          <el-button link type="primary" @click="addDevice">
            添加设备
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSceneList,
  createScene,
  updateScene,
  deleteScene,
  activateScene
} from '@/api/scene'
import { getDeviceList } from '@/api/device'

const scenes = ref([])
const devices = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const form = ref({
  name: '',
  description: '',
  devices: []
})

const loadScenes = async () => {
  loading.value = true
  try {
    scenes.value = await getSceneList()
  } finally {
    loading.value = false
  }
}

const loadDevices = async () => {
  devices.value = await getDeviceList()
}

const handleAdd = () => {
  form.value = {
    name: '',
    description: '',
    devices: []
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该场景吗？')
    await deleteScene(row.id)
    ElMessage.success('删除成功')
    await loadScenes()
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e)
    }
  }
}

const handleActivate = async (row) => {
  try {
    await activateScene(row.id)
    ElMessage.success('场景激活成功')
    await loadScenes()
  } catch (e) {
    console.error(e)
  }
}

const addDevice = () => {
  form.value.devices.push({
    deviceId: null,
    targetStatus: false
  })
}

const removeDevice = (index) => {
  form.value.devices.splice(index, 1)
}

const handleSubmit = async () => {
  try {
    if (form.value.id) {
      await updateScene(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createScene(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await loadScenes()
  } catch (e) {
    console.error(e)
  }
}

onMounted(() => {
  loadScenes()
  loadDevices()
})
</script>

<style lang="scss" scoped>
.scene-list {
  .header {
    margin-bottom: 20px;
  }

  .device-item {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;

    .el-select {
      width: 200px;
    }
  }
}
</style> 